// task/performance_task.rs
use crate::client::http_client::{send_request, Response};
use crate::stats::stats_collector::Stats;
use reqwest::Method;
use std::sync::{Arc, Mutex};
use std::time::Instant;

pub async fn run_performance_test(
    url: &str,
    endpoints: Vec<String>,
    total_requests: usize,
    concurrency: usize,
    request_interval: u64,
    timeout: u64,
    stats: Arc<Mutex<Stats>>,
) {
    let mut handles = vec![];

    for _ in 0..concurrency {
        let url = url.to_string();
        let endpoints = endpoints.clone();
        let stats = stats.clone();

        let handle = tokio::spawn(async move {
            for _ in 0..total_requests / concurrency {
                let endpoint = &endpoints[0];  // 假设我们选择第一个接口进行测试
                let url = format!("{}/{}", url, endpoint);
                let start_time = Instant::now();

                // 发送请求并记录统计信息
                let response = send_request(Method::GET, &url, None).await;

                let duration = start_time.elapsed().as_millis() as u64;
                let mut stats = stats.lock().unwrap();

                match response {
                    Ok(_) => {
                        stats.log_request(true, duration);
                    }
                    Err(_) => {
                        stats.log_request(false, duration);
                    }
                }

                // 模拟请求间隔
                tokio::time::sleep(std::time::Duration::from_millis(request_interval)).await;
            }
        });

        handles.push(handle);
    }

    // 等待所有任务完成
    for handle in handles {
        handle.await.unwrap();
    }
}
